package walker

import (
	"fmt"
	"iptv_server/v3/src/models/homevideo_model"
	"path"
	"strings"
)

const (
	// SITE_ROOTDIR  string = "." //TODO
	groupInfoFile string = "group_name.txt"

	doubanJson = "__douban_info.json"
	picName    = "__poster.jpg"
)

var (
	siteNull *site = &site{
		ID:      0,
		RootDir: "",
	}
)

type site struct {
	// homevideo_model.Home
	ID   int
	Name string
	Key  string

	RootDir string

	Groups []*group
}

// func (st *site) PathJoin(ps ...string) string {
// 	return path.Join(st.RootDir, path.Join(ps...))
// }

func (st *site) FindGroups() {
	ds, _ := listDir2(st.RootDir)
	for _, d := range ds {
		dir := d.Name()
		if strings.HasSuffix(dir, "..off") {
			continue
		}

		// TODO  debug : 记得去掉这3行
		// if !strings.HasSuffix(dir, "..move") {
		if !strings.HasPrefix(dir, "group_") {
			continue
		}

		infofile := path.Join(st.RootDir, dir, groupInfoFile)
		if !IsExists(infofile) {
			continue
		}

		name := dir
		if name2, err := GetFirstNotEmptyLine(infofile); err == nil {
			name = name2
		}
		fmt.Printf("group name: %v\n", name)
		g := groupBuilder.NewGroup(name, path.Join(st.RootDir, dir), "", st)
		st.Groups = append(st.Groups, g)
	}
}

// go: failed to trim cache: open .cache/go-build/trim.txt: permission denied
func (st *site) JustDoIt_Walk() {
	// find
	st.FindGroups()
	for i, g := range st.Groups {
		fmt.Printf("i:%v g.Name: %v\n", i, g.Name)
		g.FindVods()
		for _, v := range g.Vods {
			v.FindVideos()
		}
		for _, sub_g := range g.SubGroups {
			sub_g.FindVods()
			for _, v := range sub_g.Vods {
				v.FindVideos()
			}
		}

	}

}

func (st *site) Save(ids *IDS) {
	if st.ID < 1 {
		panic("site id must > 0, siteId==0 is for sub folders")
	}

	/// 一个 site 一个 home
	home := &homevideo_model.Home{
		ID:   uint(st.ID),
		Name: st.Name,
		Key:  st.Key,
	}

	home.Save()
	///////////////////////
	if ids == nil {
		ids = &IDS{
			gid: 0,
			vid: 0,
			pid: 0,
		}
	}

	var parentID uint = 0

	saveGroups(st.Groups,
		uint(st.ID), ids, parentID)
}
